# ========================================
#   电商平台微服务启动脚本 - 修复版
# ========================================
# 说明：此脚本解决了编码问题和指令识别问题
# 注意：需要以管理员权限运行或在执行前修改执行策略

# 检查执行策略，如果受限则尝试绕过
if ((Get-ExecutionPolicy) -eq "Restricted") {
    Write-Host "检测到受限执行策略，尝试无限制执行..." -ForegroundColor Yellow
    try {
        # 尝试以无限制方式执行
        powershell -ExecutionPolicy Bypass -File "$PSCommandPath"
        exit
    } catch {
        Write-Host "需要修改执行策略，请以管理员身份运行以下命令：" -ForegroundColor Red
        Write-Host "Set-ExecutionPolicy RemoteSigned -Scope CurrentUser" -ForegroundColor White
        Write-Host "按任意键退出..." -ForegroundColor Yellow
        $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
        exit 1
    }
}

# 设置项目根目录
$PROJECT_ROOT = "F:\shopping"

# 设置Nacos服务器地址
$NACOS_SERVER_ADDR = "192.168.5.111:8848"
$NACOS_GRPC_ADDR = "192.168.5.111:9848"

Write-Host "========================================" -ForegroundColor Green
Write-Host "   电商平台微服务启动脚本" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""

# 设置控制台编码为UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8

# 检查前置条件
Write-Host "检查前置条件..." -ForegroundColor Yellow

# 检查Java环境
try {
    $javaVersion = java -version 2>&1
    Write-Host "✓ Java环境: $($javaVersion[0])" -ForegroundColor Green
} catch {
    Write-Host "✗ 错误: 未找到Java环境，请确保已安装Java并配置了JAVA_HOME环境变量" -ForegroundColor Red
    Write-Host "按任意键退出..." -ForegroundColor Yellow
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit 1
}

# 检查Maven环境
try {
    $mvnVersion = mvn -version 2>&1
    Write-Host "✓ Maven环境: $($mvnVersion[0])" -ForegroundColor Green
} catch {
    Write-Host "✗ 错误: 未找到Maven环境，请确保已安装Maven" -ForegroundColor Red
    Write-Host "按任意键退出..." -ForegroundColor Yellow
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit 1
}

# 检查Nacos服务
Write-Host "检查Nacos服务($NACOS_SERVER_ADDR)..." -ForegroundColor Yellow
try {
    $nacosHost = $NACOS_SERVER_ADDR.Split(':')[0]
    $nacosPort = $NACOS_SERVER_ADDR.Split(':')[1]
    $nacosCheck = Test-NetConnection -ComputerName $nacosHost -Port $nacosPort -InformationLevel Quiet
    if ($nacosCheck) {
        Write-Host "✓ Nacos服务可用" -ForegroundColor Green
    } else {
        Write-Host "⚠ Nacos服务不可用，请确保Nacos已启动" -ForegroundColor Yellow
    }
} catch {
    Write-Host "⚠ 无法检查Nacos服务" -ForegroundColor Yellow
}

# 检查Redis服务
Write-Host "检查Redis服务(localhost:6379)..." -ForegroundColor Yellow
try {
    $redisCheck = Test-NetConnection -ComputerName "localhost" -Port 6379 -InformationLevel Quiet
    if ($redisCheck) {
        Write-Host "✓ Redis服务可用" -ForegroundColor Green
    } else {
        Write-Host "⚠ Redis服务不可用，请确保Redis已启动" -ForegroundColor Yellow
    }
} catch {
    Write-Host "⚠ 无法检查Redis服务" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "正在编译项目..." -ForegroundColor Yellow
Write-Host ""

# 函数：编译服务
function Compile-Service {
    param($serviceName, $servicePath)
    
    Write-Host "编译 $serviceName..." -ForegroundColor Cyan
    
    # 保存当前目录
    $currentDir = Get-Location
    
    try {
        Set-Location $servicePath
        
        # 清理并编译
        $compileResult = mvn clean package -DskipTests -q
        
        if ($LASTEXITCODE -eq 0) {
            Write-Host "✓ $serviceName 编译成功" -ForegroundColor Green
            return $true
        } else {
            Write-Host "✗ $serviceName 编译失败" -ForegroundColor Red
            return $false
        }
    } catch {
        Write-Host "✗ $serviceName 编译错误: $($_.Exception.Message)" -ForegroundColor Red
        return $false
    } finally {
        Set-Location $currentDir
    }
}

# 按顺序编译所有服务
$services = @(
    @{Name = "common-module"; Path = "$PROJECT_ROOT\common-module"},
    @{Name = "auth-service"; Path = "$PROJECT_ROOT\auth-service"},
    @{Name = "user-service"; Path = "$PROJECT_ROOT\user-service"},
    @{Name = "product-service"; Path = "$PROJECT_ROOT\product-service"},
    @{Name = "order-service"; Path = "$PROJECT_ROOT\order-service"},
    @{Name = "gateway-service"; Path = "$PROJECT_ROOT\gateway-service"}
)

foreach ($service in $services) {
    if (-not (Compile-Service $service.Name $service.Path)) {
        Write-Host "编译失败，按任意键退出..." -ForegroundColor Red
        $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
        exit 1
    }
    Start-Sleep -Seconds 2
}

Write-Host ""
Write-Host "所有模块编译成功！" -ForegroundColor Green
Write-Host ""
Write-Host "正在启动服务..." -ForegroundColor Yellow
Write-Host ""

# 函数：启动服务
function Start-Microservice {
    param($serviceName, $servicePath, $jarName, $port)
    
    Write-Host "启动 $serviceName (端口: $port)..." -ForegroundColor Cyan
    
    try {
        # 使用PowerShell直接启动，避免cmd编码问题
        $javaProcess = Start-Process -FilePath "java" 
            -ArgumentList "-jar", "$servicePath\target\$jarName" 
            -WorkingDirectory $servicePath 
            -WindowStyle Normal 
            -PassThru
            -Environment @{
                "NACOS_SERVER_ADDR" = $NACOS_SERVER_ADDR;
                "NACOS_GRPC_ADDR" = $NACOS_GRPC_ADDR
            }
        
        Write-Host "✓ $serviceName 启动中..." -ForegroundColor Green
        return $javaProcess.Id
    } catch {
        Write-Host "✗ $serviceName 启动失败: $($_.Exception.Message)" -ForegroundColor Red
        return $null
    }
}

# 启动所有服务
$serviceProcesses = @{}

# 启动顺序：先启动基础服务，最后启动网关
$servicesToStart = @(
    @{Name = "auth-service"; Path = "$PROJECT_ROOT\auth-service"; Jar = "auth-service-1.0.0.jar"; Port = 8084},
    @{Name = "user-service"; Path = "$PROJECT_ROOT\user-service"; Jar = "user-service-1.0.0.jar"; Port = 8081},
    @{Name = "product-service"; Path = "$PROJECT_ROOT\product-service"; Jar = "product-service-1.0.0.jar"; Port = 8082},
    @{Name = "order-service"; Path = "$PROJECT_ROOT\order-service"; Jar = "order-service-1.0.0.jar"; Port = 8083},
    @{Name = "gateway-service"; Path = "$PROJECT_ROOT\gateway-service"; Jar = "gateway-service-1.0.0.jar"; Port = 8080}
)

foreach ($service in $servicesToStart) {
    $pid = Start-Microservice $service.Name $service.Path $service.Jar $service.Port
    if ($pid) {
        $serviceProcesses[$service.Name] = $pid
    }
    Start-Sleep -Seconds 8  # 给服务足够的时间启动
}

Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "   所有服务启动完成！" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "服务状态：" -ForegroundColor Yellow
foreach ($service in $servicesToStart) {
    $status = if ($serviceProcesses[$service.Name]) { "✓ 运行中 (PID: $($serviceProcesses[$service.Name]))" } else { "✗ 启动失败" }
    Write-Host "- $($service.Name): $status (端口: $($service.Port))" -ForegroundColor White
}

Write-Host ""
Write-Host "访问地址：" -ForegroundColor Yellow
Write-Host "- 网关服务: http://localhost:8080" -ForegroundColor White
Write-Host "- Nacos控制台: http://$NACOS_SERVER_ADDR/nacos" -ForegroundColor White
Write-Host "- 认证服务: http://localhost:8084" -ForegroundColor White
Write-Host "- 用户服务: http://localhost:8081" -ForegroundColor White
Write-Host "- 产品服务: http://localhost:8082" -ForegroundColor White
Write-Host "- 订单服务: http://localhost:8083" -ForegroundColor White

Write-Host ""
Write-Host "管理命令：" -ForegroundColor Yellow
Write-Host "- 查看服务日志: 在对应的命令窗口查看" -ForegroundColor White
Write-Host "- 停止服务: 关闭对应的命令窗口" -ForegroundColor White
Write-Host "- 重新启动: 再次运行此脚本" -ForegroundColor White

Write-Host ""
Write-Host "按任意键退出此脚本（服务会继续运行）..." -ForegroundColor Yellow
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")